
//引入小图标
import { SearchOutlined, FolderAddOutlined } from '@ant-design/icons';
//引入antd
import { Button, Input, Pagination, ConfigProvider, Modal, Switch, InputNumber, Empty } from 'antd';
//引入汉化
import zhCN from 'antd/es/locale/zh_CN';
//引入react
import React, { useState, useEffect } from 'react';
//引入fetch请求
import { getRole, amendRoleStatus, getSearch, removeRole, insertRole, amendRole } from '../../api/index';
//引入时间格式化
import { now } from '../../utils/newTime';
//引入树状选择
import TreeSelects from '../../components/TreeSelect';
import RemoveModal from '../../components/Role/removeModal';
//引入样式
import './role.css';
function Role() {
    //角色数据
    const [role, setRole] = useState([])
    const [roles, setRoles] = useState([])
    const [roleIndex, setRoleIndex] = useState(0)
    //删除
    const [removeId, setRemoveId] = useState(null)
    //弹出框是否显示
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isModalRemove, setIsModalRemove] = useState(false)
    const [isModalAmend, setIsModalAmend] = useState(false);
    //分页
    const [pages, setPages] = useState(1);
    const [pageSizes, setPageSizes] = useState(10);
    //搜索
    const [search, setSearch] = useState('')
    //新增 角色名称
    const [name, setName] = useState()
    //角色标识
    const [roleIdentification, setRoleIdentification] = useState()
    //角色排序
    const [roleRank, setRoleRank] = useState(1)
    //角色权限
    const [rolePrivileges, setRolePrivileges] = useState()
    //角色id
    const [roleId,setRoleId] = useState()
    //useEffect获取role数据
    useEffect(() => {
        getRole()
            .then((data) => {
                setRole([...data])
            })
    }, [])
    //初始化
    useEffect(() => {
        setRoleIndex(role.length);
        if (pages == 1) {
            setRoles(role.slice(0, parseInt(pages) * parseInt(pageSizes)))
        } else {
            setRoles(role.slice(parseInt(pages - 1) * parseInt(pageSizes), parseInt(pages) * parseInt(pageSizes)))
        }
    }, [role, pages, pageSizes])
    //分页
    const onChange = (page, pageSize) => {
        setPages(page == 0 ? 1 : page)
        setPageSizes(pageSize)
        if (page == 1) {
            setRoles(role.slice(0, parseInt(page) * parseInt(pageSize)))
        } else {
            setRoles(role.slice(parseInt(page - 1) * parseInt(pageSize), parseInt(page) * parseInt(pageSize)));
        }
    };
    //搜索内容
    const handleChangeSearch = (e) => {
        setSearch(e.target.value);
    }
    //点击搜索
    const handleClickSearch = () => {
        if (search !== '') {
            getSearch({ name: search }).then((res) => {
                setRole(res);
                setSearch('')
            })
        }
    }
    //滑动开关
    const onChangeSwitch = (index) => {
        let roleArr = role
        roleArr.forEach((item) => {
            if (item.id == index) {
                amendRoleStatus({ id: item.id, roleStatus: !item.roleStatus })
                    .then((res) => {

                    })
                item.roleStatus = !item.roleStatus
            }
        })
        setRole([...roleArr])
    };
    //排序
    const onChangeRank = (value) => {
        setRoleRank(value);
    };
    //角色名称
    const onChangeName = (e) => {
        setName(e.target.value);
    };
    //角色标识
    const onChangeRoleIdentification = (e) => {
        setRoleIdentification(e.target.value);
    };
    //角色权限
    const onChangRolePrivileges = (val) => {
        setRolePrivileges(val);
    };
    //弹出框
    const showModal = () => {
        setIsModalVisible(true);
    };

    const handleOk = () => {
        insertRole({ name, roleRank, rolePrivileges, roleIdentification }).then((res) => {
            if (res.code == 200) {
                setName('');
                setRoleRank(1);
                setRolePrivileges([]);
                setRoleIdentification('');
                getRole()
                    .then((data) => {
                        setRole([...data])
                    })
            }

        })
        setIsModalVisible(false);
    };

    const handleCancel = () => {
        setName('');
        setRoleRank(1);
        setRolePrivileges([]);
        setRoleIdentification('');
        setIsModalVisible(false);
    };
    //修改弹出框
    const showModalAmend = (id) => {
        role.forEach((item, index) => {
            if (item.id == id) {
                setName(item.name);
                setRoleRank(item.roleRank);
                setRolePrivileges(JSON.parse(item.rolePrivileges));
                setRoleIdentification(item.roleIdentification);
            }
        })
        setRoleId(id)
        setIsModalAmend(true);
    };

    const handleOkAmend = () => {
        amendRole({ name, roleRank, rolePrivileges, roleIdentification,roleId }).then((res) => {
            if (res.code == 200) {
                setName('');
                setRoleRank(1);
                setRolePrivileges([]);
                setRoleIdentification('');
                getRole()
                    .then((data) => {
                        setRole([...data])
                    })
            }
        })
        setIsModalAmend(false);
    };

    const handleCancelAmend = () => {
        setName('');
        setRoleRank(1);
        setRolePrivileges([]);
        setRoleIdentification('');
        setIsModalAmend(false);
    };
    //删除弹出框
    const showModalRemove = (id) => {
        setRemoveId(id)
        setIsModalRemove(true);
    };

    const handleOkRemove = () => {
        let roleArr = role
        removeRole({ id: removeId })
            .then((res) => {
                roleArr.forEach((item, index) => {
                    if (item.id == removeId) {
                        roleArr.splice(index, 1)
                        setRole([...roleArr])
                    }
                })
                console.log(res);
            })
        setIsModalRemove(false);
    };

    const handleCancelRemove = () => {
        setIsModalRemove(false);
    };
    return (
        <div className="role">
            {/* 头部 */}
            <header className='header'>
                <div>
                    {/* 搜索 */}
                    <Input onChange={(e) => { handleChangeSearch(e) }} value={search} style={{ width: '226px', height: '40px', borderRadius: '5px', marginRight: '14px' }} placeholder="请输入角色名称" />
                    <Button onClick={handleClickSearch} style={{ backgroundColor: '#409EFE', color: '#fff', border: 'none', height: '40px', borderRadius: '5px', marginRight: '14px' }} type="primary" icon={<SearchOutlined />}>
                        查询
                    </Button>
                    {/* 添加角色 */}
                    <Button type="primary" onClick={showModal} style={{ backgroundColor: '#6AC037', color: '#fff', border: 'none', height: '40px', borderRadius: '5px' }} icon={<FolderAddOutlined />}>
                        新增角色
                    </Button>
                </div>
            </header>
            <main className='main'>
                <table>
                    <thead>
                        <tr>
                            <th>序号</th>
                            <th>角色名称</th>
                            <th>角色标识</th>
                            <th>排序</th>
                            <th>角色状态</th>
                            {/* <th>角色描述</th> */}
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {role.length !== 0 ?
                            roles.map((item, index) => {
                                return (
                                    <tr key={item.id}>
                                        <td>{item.id}</td>
                                        <td>{item.name}</td>
                                        <td>{item.roleIdentification}</td>
                                        <td>{item.roleRank}</td>
                                        <td>
                                            {
                                                item.id == 1
                                                    ? <Switch checked={item.roleStatus} disabled />
                                                    : <Switch checked={item.roleStatus} onChange={() => { onChangeSwitch(item.id) }} />
                                            }
                                        </td>
                                        {/* <td>测试角色1</td> */}
                                        <td>{now(item.createTime)}</td>
                                        <td>
                                            {
                                                item.name == '超级管理员' ?
                                                    <><span style={{ margin: '12px' }}>修改</span><span>删除</span></> :
                                                    <><span className='color' style={{ margin: '12px' }} onClick={() => { showModalAmend(item.id) }}>修改</span><span className='color' onClick={() => { showModalRemove(item.id) }}>删除</span></>
                                            }
                                        </td>
                                    </tr>
                                )
                            })
                            : <tr><td colSpan={6}><ConfigProvider locale={zhCN}><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /></ConfigProvider></td></tr>
                        }
                    </tbody>
                </table>
            </main>
            <footer>
                <ConfigProvider locale={zhCN}>
                    <Pagination
                        total={roleIndex}
                        showSizeChanger
                        showQuickJumper
                        defaultCurrent={1}
                        showTotal={(total) => `共${total}条`}
                        onChange={onChange}
                    />
                </ConfigProvider>
            </footer>
            {/* 模态框 */}
            <Modal title="新增角色" visible={isModalVisible} cancelText="取消" okText="确定" onOk={handleOk} onCancel={handleCancel}>
                <div style={{ margin: '20px 0' }} className='modalName'>
                    角色名称：<Input style={{ width: '360px' }} value={name} onChange={onChangeName} placeholder="请输入角色名称" />
                </div>
                <div style={{ margin: '20px 0' }} className='modalName'>
                    角色标识：<Input style={{ width: '360px' }} value={roleIdentification} onChange={onChangeRoleIdentification} placeholder="请输入角色标识" />
                </div>
                <div style={{ margin: '20px 0' }} className='modalName'>
                    排序：<InputNumber min={1} max={10} defaultValue={1} value={roleRank} onChange={onChangeRank} />
                </div>
                <div style={{ margin: '20px 0' }} className='modalName'>
                    选择权限：<TreeSelects rolePrivileges={rolePrivileges} onChangRolePrivileges={onChangRolePrivileges} />
                </div>
            </Modal>
            <Modal title="修改角色" visible={isModalAmend} cancelText="取消" okText="确定" onOk={handleOkAmend} onCancel={handleCancelAmend}>
                <div style={{ margin: '20px 0' }} className='modalName'>
                    角色名称：<Input style={{ width: '360px' }} value={name} onChange={onChangeName} placeholder="请输入角色名称" />
                </div>
                <div style={{ margin: '20px 0' }} className='modalName'>
                    角色标识：<Input style={{ width: '360px' }} value={roleIdentification} onChange={onChangeRoleIdentification} placeholder="请输入角色标识" />
                </div>
                <div style={{ margin: '20px 0' }} className='modalName'>
                    排序：<InputNumber min={1} max={10} defaultValue={1} value={roleRank} onChange={onChangeRank} />
                </div>
                <div style={{ margin: '20px 0' }} className='modalName'>
                    选择权限：<TreeSelects rolePrivileges={rolePrivileges} onChangRolePrivileges={onChangRolePrivileges} />
                </div>
            </Modal>
            <Modal title="删除角色" visible={isModalRemove} cancelText="取消" okText="确定" onOk={handleOkRemove} onCancel={handleCancelRemove}>
                <div>是否删除该角色</div>
            </Modal>
        </div>
    )
}
export default Role;